HackerRank Pairs
https://www.hackerrank.com/challenges/pairs/problem
提出
code: python
#!/bin/python3
import math
import os
import random
import re
import sys
import itertools
#
# Complete the 'pairs' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER k
# 2. INTEGER_ARRAY arr
#
def pairs(k, arr):
# Write your code here
arr.sort()
# arr is not sequence
ans = 0
for i in itertools.combinations(arr, 2):
if (abs(i0 - i1) == k):
ans += 1
return ans
if __name__ == '__main__':
fptr = open(os.environ'OUTPUT_PATH', 'w')
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input0)
k = int(first_multiple_input1)
arr = list(map(int, input().rstrip().split()))
result = pairs(k, arr)
fptr.write(str(result) + '\n')
fptr.close()
解答
code: python
#!/bin/python3
import math
import os
import random
import re
import sys
from collections import Counter
#
# Complete the 'pairs' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER k
# 2. INTEGER_ARRAY arr
#
def pairs(k, arr):
# Write your code here
d = Counter(arr)
pairs = 0
for i in arr:
# 3 -> 1+2
if i+k in d:
pairs += 1
# 3 -> 5-2
if i-k in d:
pairs += 1
# solve duplicate
del di
return pairs
if __name__ == '__main__':
fptr = open(os.environ'OUTPUT_PATH', 'w')
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input0)
k = int(first_multiple_input1)
arr = list(map(int, input().rstrip().split()))
result = pairs(k, arr)
fptr.write(str(result) + '\n')
fptr.close()
メモ
https://www.youtube.com/watch?v=bkFToMC1Q10
提出
code: python
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'pairs' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER k
# 2. INTEGER_ARRAY arr
#
def pairs(k, arr):
# Write your code here
sarr = set(arr)
ans = 0
for n in arr:
if n - k in sarr:
ans += 1
if n + k in sarr:
ans += 1
return ans // 2
if __name__ == '__main__':
fptr = open(os.environ'OUTPUT_PATH', 'w')
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input0)
k = int(first_multiple_input1)
arr = list(map(int, input().rstrip().split()))
result = pairs(k, arr)
fptr.write(str(result) + '\n')
fptr.close()